package csvreader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import junit.framework.TestCase;

public class Retriever extends TestCase {

	//constructor
	public Retriever() {
	}

	//methods
	public Line getDocument(String path) {
		String s = "";
		Line line = new Line();
		Element element = new Element();
		File file = new File(path);
		FileReader filereader;
		BufferedReader bufferedreader;
		
		try {
			filereader = new FileReader(file);
			bufferedreader = new BufferedReader(filereader);
			
			
			while(s!=null){
				
				s = bufferedreader.readLine();
				if (s == null) break;
				
				element = Retriever.calculate(path,s);	
				line.addElement(element);
						
			}
		
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		return line;
	
	}
	
	public static Element calculate (String path, String s){
		
	int k = 1;
	String word = "";
	int quotes = 0;
	Element element = new Element();

	while (k <= s.length()) {
		
		x:
		while (!s.substring(k-1, k).equals(",")) {
			word = word + s.substring(k - 1, k);
			System.out.println(word+ "  "+k);		
			if (s.substring(k-1, k).equals("\""))  quotes++;	
			k++;
			if (k>s.length()) break x;
		}
				
		if (quotes % 2 == 0) {
			element.addData(word);
			k++;
			word = "";
		} else {
			word = word + ",";
			k++;
		}	
	}	
	
	return element;
	}

}